<?php

namespace app\controller;

use app\BaseController;
use app\model\File;
use app\model\Project as ProjectModel;
use app\model\ProjectData as ProjectDataModel;
use think\facade\Filesystem;

class Project extends BaseController
{
    public function list()
    {
        $list = ProjectModel::order('id', 'desc')->paginate(10);
        return ["code" => 200, "count" => $list->total(), "data" => $list->items(), "msg" => "获取成功"];
    }

    public function create()
    {
        $post = request()->post();
        $data = ProjectModel::create($post);
        return ["code" => 200, "data" => $data, "msg" => "创建成功"];
    }

    public function edit()
    {
        $post = request()->post();
        $data = ProjectModel::update($post);
        return ["code" => 200, "data" => $data, "msg" => "更新成功"];
    }

    public function delete($ids)
    {
        ProjectModel::destroy($ids);
        return ["code" => 200, "msg" => "删除成功"];
    }

    public function publish()
    {
        $post = request()->only(['id', 'state']);
        $data = ProjectModel::update($post);
        return ["code" => 200, "data" => $data, "msg" => "发布成功"];
    }

    public function read($projectId)
    {
        $data = ProjectModel::field("*,id as content")->find($projectId);
        return ["code" => 200, "data" => $data, "msg" => "获取成功"];
    }

    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('object');
        // 上传到本地服务器
        $savename = Filesystem::disk('public')->putFile('upload', $file);
        $fileData = File::createData([
            "file_name" => "/storage/" . $savename,
            "file_size" => $file->getSize(),
            "file_suffix" => $file->getMime(),
            "create_time" => date("Y-m-d H:i:s"),
            "md5" => "",
            "virtual_key" => "local",
            "relative_path" => "",
            "absolute_path" => "",
        ]);

        $data = [
            "bucketName" => null,
            "createTime" => $fileData['create_time'],
            "createUserId" => "-",
            "createUserName" => "-",
            "fileName" => "/storage/" . $savename,
            "fileSize" => $file->getSize(),
            "fileSuffix" => $file->getMime(),
            "id" => $fileData['id'],
            "updateTime" => null,
            "updateUserId" => null,
            "updateUserName" => null
        ];

        return ["code" => 200, "data" => $data, "msg" => "上传成功"];
    }

}
